package ldh.im.fxgui.pane;

import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Node;
import javafx.scene.control.Label;
import javafx.scene.layout.StackPane;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
import javafx.scene.media.MediaView;
import javafx.scene.paint.Color;
import javafx.scene.text.TextAlignment;
import ldh.im.ImConfig;
import ldh.im.dto.enums.MessageType;
import ldh.im.fxbase.data.pojo.ImMessage;
import ldh.im.fxbase.data.pojo.status.ImMessageFileStatus;
import ldh.im.fxbase.richtext.ImText;
import ldh.im.fxbase.service.AudioService;
import ldh.im.fxbase.service.AudioStreamService;
import ldh.im.fxbase.util.*;
import ldh.im.fxgui.service.DefaultFileProgressListener;
import ldh.im.fxgui.util.UiUtil;
import ldh.im.util.ConfigUtil;
import ldh.rpc.cache.CacheService;
import org.kordamp.ikonli.fontawesome.FontAwesome;
import org.kordamp.ikonli.javafx.FontIcon;

import java.io.File;
import java.text.NumberFormat;
import java.util.function.Consumer;
import java.util.function.Supplier;

/**
 * 音频面板
 */
public class AudioMessagePane extends BaseMessagePane {

    @Override
    public Node createPane(ImMessage message, boolean isReceive, boolean isRef) {
        if (message.getMessageType() != MessageType.Audio) {
            throw new RuntimeException("不支持这种消息类型" + message.getMessageType());
        }
        if (message.isSender(message.getCurrentUserId())) {
            if (message.getFileStatus() != ImMessageFileStatus.uploaded) {
                TextAlignment textAlignment = TextAlignment.LEFT; //isReceive ? TextAlignment.LEFT : TextAlignment.RIGHT;
                ImText imText = new ImText(textAlignment);
                imText.setImContent("音频正在上传中");
                return imText;
            }
        } else {
            if (message.getFileStatus() != ImMessageFileStatus.downloaded) {
                TextAlignment textAlignment = TextAlignment.LEFT; //isReceive ? TextAlignment.LEFT : TextAlignment.RIGHT;
                ImText imText = new ImText(textAlignment);
                imText.setImContent("音频正在下载中");
                return imText;
            }
        }

        StackPane anchorPane = new StackPane();
        if (isReceive) {
            anchorPane.setAlignment(Pos.CENTER_LEFT);
        } else {
            anchorPane.setAlignment(Pos.CENTER_RIGHT);
        }

        anchorPane.getStyleClass().add("im-text-pane");

        MediaView mediaView = new MediaView();

        NumberFormat numberFormat = NumberFormat.getNumberInstance();
        numberFormat.setMaximumFractionDigits(2);
        String text = "";
        if (message.getMessageExt() != null && message.getMessageExt().getTime() != null) {
            text = numberFormat.format((double)message.getMessageExt().getTime()/1000) + " 秒";
        }
        Label audioLabel = new Label(text);
//        audioLabel.setPadding(new Insets(0, 0, 0, 2));
        FontIcon fontIcon = FontIcon.of(FontAwesome.findByDescription("fa-file-sound-o"), 20, Color.GREEN);
        audioLabel.setGraphic(fontIcon);

        if (!isRef) {
            audioLabel.setOnMouseClicked(e->{
                CacheService cacheService = RpcUtil.getRpcBootstrap().getRpcConfig().getCacheService();
                String currentUserId = (String) cacheService.getCache(ImConfig.LOGIN_USER_ID);
                if (message.isReceiver(currentUserId) && message.getFileStatus() != ImMessageFileStatus.downloaded) {
                    ThreadPoolUtil.submit(()->{
                        ExceptionUtil.catchException(()->{
                            RpcUtil.getImService().downloadFile(message, new DefaultFileProgressListener(), m-> UiUtil.uiUpdateMessage(m));
                            return null;
                        });
                    });
                    return;
                }
                if (audioLabel.getUserData() != null && audioLabel.getUserData().toString().equals("playing")) return;
                audioLabel.setUserData("playing");
                String audioPath = FileUtil.getFilePath(message);
                playAudio(mediaView, audioPath, ()-> {
                    audioLabel.setUserData("end!");
                    return true;
                });
            });

            buildPopup(anchorPane, message);
        }

        anchorPane.getChildren().addAll(audioLabel, mediaView);
        anchorPane.setMaxWidth(ParamUtil.MESSAGE_WIDTH);
        return anchorPane;
    }

    void playAudio(MediaView mediaView, String audioPath, Supplier<Boolean> supplier) {
        if (audioPath == null) return;
        File file = new File(audioPath);
        Media media = new Media(file.toURI().toString());
        MediaPlayer mediaPlayer = new MediaPlayer(media);
        mediaView.setMediaPlayer(mediaPlayer);
        mediaPlayer.onEndOfMediaProperty().set(()->{
            supplier.get();
            mediaPlayer.dispose();
        });
        mediaPlayer.setAutoPlay(true);
    }

    void playAudio2(String audioPath, Supplier<Boolean> supplier) {
        AudioService audioService = new AudioStreamService(ConfigUtil.getAudioFileDir());
        audioService.playRecord(audioPath, (Void)->{
            supplier.get();
            ((AudioStreamService) audioService).closeAudio();
        });
    }
}
